package controller

import (
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"fmt"
	mssql "github.com/denisenkom/go-mssqldb"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

func MyUploadHandler(c *gin.Context) {
	// 在这里编写对 gin 上下文的处理逻辑
	w := c.Writer
	r := c.Request

	if r.Method != "POST" {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}

	// 解析表单数据，包括上传的文件
	err := r.ParseMultipartForm(10 << 20) // 设置最大文件大小为 10MB
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// 获取上传的文件
	file, handler, err := r.FormFile("file")

	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	//defer file.Close()
	FileErr := file.Close()
	if err != nil {
		// 处理错误，例如日志记录或返回错误给调用者
		log.Println("Error closing file:", FileErr)
		return
	}

	kindStr := r.FormValue("kind") // 获取表单中的 "kind" 值
	kind, _ := strconv.Atoi(kindStr)
	// 根据 "kind" 值设置不同的 uploadDir
	var uploadDir string
	switch kind {
	case 1:
		uploadDir = "./File/ClubJoinFile"
	case 2:
		uploadDir = "./File/ClubCreateFile"
	case 3:
		uploadDir = "./File/ActivityCreateFile"
	case 4:
		uploadDir = "./File/InspectionFile"
	case 5:
		uploadDir = "./File/AwardFile"
	default:
		uploadDir = "./uploads"
	}

	//uploadDir := "./uploads"

	// 检查上传目录是否存在，如果不存在则创建
	if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
		os.MkdirAll(uploadDir, os.ModePerm)
	}

	filePath := filepath.Join(uploadDir, handler.Filename)

	// 创建目标文件
	f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer f.Close()

	// 将上传的文件内容写入目标文件
	_, err = io.Copy(f, file)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// 查询数据库
	DB := common.GetDB()

	FileInfo := model.File{
		Kind:  kind,
		FName: handler.Filename,
		Url:   filePath,
	}

	//插入file数据表
	if createErr := DB.Create(&FileInfo).Error; createErr != nil {
		response.Response(c, http.StatusBadRequest, 400, nil, "插入文件信息发生错误，请重试")
		return
	} else {
		// 返回成功的响应
		fmt.Println("文件上传成功！")
	}

}

func CreateClub(ctx *gin.Context) {
	uid := ctx.PostForm("uid") //申请创建社团的用户id
	userid, _ := strconv.Atoi(uid)

	ClubName := ctx.PostForm("Cname")

	ClubType := ctx.PostForm("Type")

	Address := ctx.PostForm("Address")
	add, _ := strconv.Atoi(Address)

	CType, _ := strconv.Atoi(ClubType)

	LeaderName := ctx.PostForm("leaderName")

	LeaderID := ctx.PostForm("leaderID")
	Lid, _ := strconv.Atoi(LeaderID)

	college := ctx.PostForm("college")

	createAim := ctx.PostForm("createAim")

	TName := ctx.PostForm("teacherName")

	TeacherID := ctx.PostForm("teacherID")
	Tid, _ := strconv.Atoi(TeacherID)

	TPhone := ctx.PostForm("teacherPhone")

	AdminName := ctx.PostForm("AdminName")

	AdminID := ctx.PostForm("AdminID")
	Adminid, _ := strconv.Atoi(AdminID)

	AdminPhone := ctx.PostForm("AdminPhone")

	ClubMail := ctx.PostForm("clubMail")

	ClubPhone := ctx.PostForm("clubPhone")

	Intro := ctx.PostForm("Introduction")

	Time := ctx.PostForm("CreateTime") //申请创建社团时间

	ApplyCreateTime, _ := time.Parse("2006-01-02 15:04:05", Time) //转换时间的格式

	file := ctx.PostForm("file")
	var club_state = 0   //社团当前状态默认为全部
	var create_state = 0 //状态是审批中

	var state = 0
	// 得到所连接的数据库
	DB := common.GetDB()

	//判断社长信息是否存在于用户表users中
	var LeaderInfo model.User
	var TeacherInfo model.User
	var AdminInfo model.User

	result1 := DB.Table("users").Where("uid = ? AND uname = ?", Lid, LeaderName).First(&LeaderInfo)
	result2 := DB.Table("users").Where("uid = ? AND uname = ?", Tid, TName).First(&TeacherInfo)
	result3 := DB.Table("users").Where("uid = ? AND uname = ? AND Permission = ?", Adminid, AdminName, 2).First(&AdminInfo) //行政指导老师为超级管理员，需要负责审批工作

	//都能找到信息，能够创建社团
	if result1.RowsAffected > 0 && result2.RowsAffected > 0 && result3.RowsAffected > 0 {

		state = 1

		club := model.Club{
			Cname:             ClubName,
			Address:           add,
			Type:              CType,
			Aim:               mssql.VarChar(createAim),
			State:             club_state,
			Exist:             create_state,
			Unit:              mssql.VarChar(college),
			TeacherName:       mssql.VarChar(TName),
			TeacherID:         Tid,
			TeacherPhone:      mssql.VarChar(TPhone),
			AdminTeacherName:  mssql.VarChar(AdminName),
			AdminTeacherID:    Adminid,
			AdminTeacherPhone: mssql.VarChar(AdminPhone),
			LeaderID:          Lid,
			LeaderName:        mssql.VarChar(LeaderName),
			Mailbox:           mssql.VarChar(ClubMail),
			Phone:             mssql.VarChar(ClubPhone),
			Introduction:      mssql.VarChar(Intro),
		}

		//插入clubs数据表
		if joinErr := DB.Create(&club).Error; joinErr != nil {
			fmt.Println("执行 SQL 语句时发生错误:", joinErr)
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			return
		}

		// 获得新创建的社团的Cid
		clubID := club.Cid
		fmt.Printf("刚插入的记录的ID: %d\n", clubID)

		clubcreate := model.Apply_CreateClub{
			Cid:       clubID,
			Uid:       userid,
			ApplyTime: ApplyCreateTime,
			State:     create_state,
			File:      file,
		}

		//插入申请创建社团分表
		if applyErr := DB.Table("apply_createclub").Create(&clubcreate).Error; applyErr != nil {
			fmt.Println("执行 SQL 语句时发生错误:", applyErr)
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			return
		} else {
			// 插入成功
			fmt.Println("插入创建社团申请记录成功")
			// response成功提示给前端
			response.Response(ctx, http.StatusOK, 200, nil, "申请创建社团成功")

			applyid := clubcreate.ID
			var kind = 4

			var apply_state = 0

			Title := ClubName + "创建社团申请"

			currentTime := time.Now() //申请时间

			query3 := "INSERT INTO applies (apply_id,uid,kind,approval_state,title,apply_time)VALUES (?,?,?,?,?,?)"

			result3 := DB.Exec(query3, applyid, uid, kind, apply_state, Title, currentTime)

			if result3.Error != nil {
				fmt.Println("执行 SQL 语句时发生错误:", result3.Error)
				// response错误提示给前端
				response.Response(ctx, http.StatusBadRequest, 400, nil, "创建社团申请记录插入总表发生错误，请重试")
			}

		}

	} else if result1.RowsAffected == 0 {
		//找不到社长信息
		state = 2

		response.Success(ctx, gin.H{"state": state}, "社长信息不存在")
	} else if result2.RowsAffected == 0 {
		//找不到业务指导老师信息
		state = 3
		response.Success(ctx, gin.H{"state": state}, "业务指导老师信息不存在")
	} else if result3.RowsAffected == 0 {
		//找不到业务指导老师信息
		state = 4
		response.Success(ctx, gin.H{"state": state}, "行政指导老师信息不存在")
	} else {
		state = 0
	}

	//query2 := "INSERT INTO apply_createclub (Cid,Uid,ApplyTime,State) VALUES (?,?,?,?)"
	//
	//result2 := DB.Exec(query2, insertID, uid, ApplyCreateTime, create_state)

	//if result2.Error != nil {
	//	fmt.Println("执行 SQL 语句时发生错误:", result2.Error)
	//	// response错误提示给前端
	//	response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
	//} else {

	//}

}
